//
//  WCG_M_mainViewController.m
//  Project_B
//
//  Created by 黑黑 on 15/11/24.
//  Copyright © 2015年 Atom_Wang. All rights reserved.
//

#import "WCG_M_mainViewController.h"
#import "CollectionViewPackage.h"
#import "GXSuggestModel.h"
#import "GXiaNetHandle.h"
#import "WCG_M_AutoDetailViewController.h"
#import "GXTipsButtonView.h"
#import "MJRefresh.h"
#import "GXSuggestArticelTableViewCell.h"
#import "GXSuggestImageViewTableViewCell.h"
#import "GXProviderDetailTableViewCell.h"
#import "NSString+GXSizeWithText.h"
#import "WCG_M_NoonTeaViewController.h"
#import "GXDailyModel.h"

static NSString *articleCellID = @"SuggestArticleCell";
static NSString *poetryCellID = @"SuggestPoetryCell";
static NSString *articleNoCellID = @"SuggestArticleNoCell";

@interface WCG_M_mainViewController () <UITableViewDataSource, UITableViewDelegate, CollectionViewClickedProtocol, UIScrollViewDelegate>

//  轮播图数据
@property (nonatomic, retain) NSMutableArray *autoScrollArr;
//  轮播图
@property (nonatomic, retain) CollectionViewPackage *autoScrollView;
//  瀑布流数据
@property (nonatomic, retain) NSMutableArray *waterfallArr;
//  用于瀑布流刷新数据
@property (nonatomic, retain) NSDictionary *next;
//  总数据数组
@property (nonatomic, retain) NSMutableArray *allWaterfallArr;
//  下午茶按钮
@property (nonatomic, retain) GXTipsButtonView *afternoonTeaBtn;
@property (nonatomic, retain) GXDailyModel *dailyModel;

@end

@implementation WCG_M_mainViewController

#pragma mark - 视图将要出现
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    //  push 回来的时候 开启定时器
    [self.autoScrollView openTimer];
    [self navi];
    self.navigationController.navigationBarHidden = NO;
    self.navigationController.navigationBar.barTintColor = [UIColor grayColor];
    
    //  出现 tabBar
    NSArray *temp = self.tabBarController.view.subviews;
    UIView *view = temp[2];
    [UIView animateWithDuration:1.0f animations:^{
        view.frame = CGRectMake(0, kScreenHeight - 49, kScreenWidth, 49);
    }];
}

#pragma mark - 视图将要消失
- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    //  跳转至其他页面 关闭定时器
    [self.autoScrollView timerInvalidate];
}

#pragma mark - 视图加载完成
- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.title = @"今日推荐";
    self.view.backgroundColor = [UIColor whiteColor];
    
    //  创建 tableView
    [self createTableView];
    //  创建下午茶按钮
    [self createTeaButton];
    //  小菊花
    [self loadNightMBProgress];
    //  创建 tableView
    [self getSuggestData];
    [self getDailyModelData];
    //  上拉加载
    self.tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        [self loadMoreData];
    }];
    [self.navigationController.navigationBar setShadowImage:[UIImage new]];
}

#pragma mark - 请求网络数据
#pragma mark - 轮播图数据
- (void)getSuggestData {
    
    //  初始化数组
    self.autoScrollArr = [NSMutableArray array];
    self.waterfallArr = [NSMutableArray array];
    
    //  多线程请求数据
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.f * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        
#pragma mark - 请求轮播图数据
        [GXiaNetHandle getUrl:kSuggestScrollWeb
                       cookie:nil
                      success:^(id result) {
                          //    遍历数据中的字典
                          for (NSDictionary *dic in result[@"data"]) {
                              //    将轮播图数据添加到数组中
                              [self.autoScrollArr addObject:[GXSuggestModel modelWithDic:dic[@"item"]]];
                          }
                          //    创建轮播图
                          [self createAutoView];
                      } failure:^(NSError *error) {
                          NSLog(@"轮播图数据请求错误: %@", error);
                      }];
        
#pragma mark - 请求瀑布流数据
        [GXiaNetHandle getUrl:kSuggestFirstWeb
                       cookie:nil
                      success:^(id result) {
                          //    移除小菊花
                          [self removeHud];
                          //    保存用于刷新数据的字典
                          self.next = result[@"next"];
                          //    遍历
                          for (NSDictionary *dic in result[@"waterfall"]) {
                              //   字典没有 item的数据不要
                              if (dic[@"item"]) {
                                  //    13广告 4官方日签 跳过
                                  if ([dic[@"item"][@"type"] integerValue] == 13
                                      || [dic[@"item"][@"type"] integerValue] == 4)
                                      continue;
                                  //    将帅选过后的数据添加到数组
                                  [self.waterfallArr addObject:[GXSuggestModel modelWithDic:dic[@"item"]]];
                              }
                          }
                          //    将当天的数据添加到总数组中
                          self.allWaterfallArr = [NSMutableArray arrayWithArray:self.waterfallArr];
                          //    如果数组有值 刷新视图
                          self. allWaterfallArr.count != 0 ? [self.tableView reloadData] : nil;
        } failure:^(NSError *error) {
            NSLog(@"瀑布流数据请求错误: %@", error);
        }];
    });
}

#pragma mark - 上拉加载
- (void)loadMoreData {
    //  初始化数组
    NSMutableArray *tempArr = [NSMutableArray array];
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.f * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        //  拼接 请求旧数据
        [GXiaNetHandle getUrl:[NSString stringWithFormat:kSuggestWeb, self.next[@"page"], self.next[@"w_datetime"]]
                       cookie:nil
                      success:^(id result) {
                          //    将当前的 next 置空
                          self.next = nil;
                          //    得到新的 next
                          self.next = result[@"next"];
                          //遍历数组中的字典
                          for (NSDictionary *dic in result[@"waterfall"]) {
                              //遍历字典中的 item
                              if (dic[@"item"]) {
                                  //13-广告类型 4-官方日签
                                  if ([dic[@"item"][@"type"] integerValue] == 13
                                      || [dic[@"item"][@"type"] integerValue] == 4)
                                      continue;
                                  //字典转模型
                                  [tempArr addObject:[GXSuggestModel modelWithDic:dic[@"item"]]];
                              }
                          }
                          //    添加到总数组
                          [self.allWaterfallArr addObjectsFromArray:tempArr];
                          //    如果数组不为空
                          if (self.allWaterfallArr.count) {
                              //    刷新视图
                              [self.tableView reloadData];
                          }
                          //    停止刷新
                          [self.tableView.mj_footer endRefreshing];
        } failure:^(NSError *error) {
            NSLog(@"瀑布流数据上拉加载请求错误: %@", error);
        }];
    });
}

#pragma mark - 创建视图
#pragma mark - 创建 tableView
- (void)createTableView {
    //  创建
    [self createTableViewWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight - 49)];
    //  代理
    self.tableView.delegate = self;
    //  数据源
    self.tableView.dataSource = self;
    //  取消滚动条
    self.tableView.showsVerticalScrollIndicator = NO;
    //  注册 cell
    //注册文章 cell
    [self.tableView registerClass:[GXSuggestArticelTableViewCell class]
           forCellReuseIdentifier:articleCellID];
    //注册诗歌 cell
    [self.tableView registerClass:[GXSuggestImageViewTableViewCell class]
           forCellReuseIdentifier:poetryCellID];
    //不推荐文章
    [self.tableView registerClass:[GXProviderDetailTableViewCell class]
           forCellReuseIdentifier:articleNoCellID];
}

#pragma mark - 创建轮播图
- (void)createAutoView {
    //  轮播图占当前页面的一半
    self.autoScrollView = [[CollectionViewPackage alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight / 2)];
    //  设置轮播图代理
    self.autoScrollView.delegate = self;
    //  将轮播图作为 tableView 的头部视图
    self.tableView.tableHeaderView = self.autoScrollView;
    //  赋值
    self.autoScrollView.dataArr = [NSMutableArray arrayWithArray:self.autoScrollArr];
    //  开启定时器 轮播图开始轮播
    [self.autoScrollView openTimer];
}

#pragma mark - 下午茶按钮创建
- (void)createTeaButton {
    //设置下午茶
    self.afternoonTeaBtn = [[GXTipsButtonView alloc] initWithFrame:CGRectMake(kScreenWidth - 70, 45, 50, 60)];
    //设置图片
    [self.afternoonTeaBtn.button setImage:[UIImage imageNamed:@"icon-afternoon-tea-entry"]
                                 forState:UIControlStateNormal];
    //小图
    [self.afternoonTeaBtn.imageView setImage:[UIImage imageNamed:@"icon-has-new-tea"]];
    //添加下午茶响应事件
    [self.afternoonTeaBtn addTarget:self
                             action:@selector(afternonnTeaButtonAction)];
    //添加到视图
    [self.view addSubview:self.afternoonTeaBtn];
    //将下午茶放在最前端
    [self.view bringSubviewToFront:self.afternoonTeaBtn];
}

#pragma mark - tableView delegate
//  一共有几行
- (NSInteger)tableView:(UITableView *)tableView
 numberOfRowsInSection:(NSInteger)section {
    
    return self.allWaterfallArr.count != 0 ? self.allWaterfallArr.count : 0;
}

//  每行显示什么
- (UITableViewCell *)tableView:(UITableView *)tableView
         cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    //重用文章 cell
    GXSuggestArticelTableViewCell *articleCell = [tableView dequeueReusableCellWithIdentifier:articleCellID];
    //重用诗歌 cell
    GXSuggestImageViewTableViewCell *poetryCell = [tableView dequeueReusableCellWithIdentifier:poetryCellID];
    //不推荐文章 cell
    GXProviderDetailTableViewCell *providerCell = [tableView dequeueReusableCellWithIdentifier:articleNoCellID];
    
    //取得推荐模型
    GXSuggestModel *suggestModel = self.allWaterfallArr[indexPath.row];
    
    //九宫格 大型画册 视频
    if (suggestModel.type.integerValue == 1
        || suggestModel.type.integerValue == 2
        || suggestModel.type.integerValue == 9
        || suggestModel.type.integerValue == 10) {
        
        articleCell.suggestModel = suggestModel;
        return articleCell;
    }
    
    //文章
    else if (suggestModel.type.integerValue == 0) {
        
        //推荐文章
        if (suggestModel.is_recommended == true) {
            articleCell.suggestModel = suggestModel;
            return articleCell;
        }
        
        //不推荐文章
        else {
            providerCell.suggestModel = suggestModel;
            return providerCell;
        }
    }
    
    //大图 cell
    else if (suggestModel.type.integerValue == 5
             || suggestModel.type.integerValue == 6){
        
        poetryCell.suggestModel = suggestModel;
        return poetryCell;
    }
    
    return poetryCell;
}

//tableView 行高
- (CGFloat)tableView:(UITableView *)tableView
heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    GXSuggestModel *suggestModel = self.allWaterfallArr[indexPath.row];
    
    //文本宽度
    CGFloat titleW = kScreenWidth - 25 - [UIImage imageNamed:@"icon-image-album"].size.width;
    //标题文本高度
    CGRect titleSize = [suggestModel.title SizeWithTextFontSize:kSuggestTitleFontSize
                                                      textWidth:titleW];
    //副标题文本高度
    CGRect subTitleSize = [suggestModel.content[@"desc"] SizeWithTextFontSize:KSuggestIntroFontSize
                                                                    textWidth:titleW];
    
    //音乐/大型画册/九宫格/视频
    if (suggestModel.type.integerValue == 10
        || suggestModel.type.integerValue == 9
        || suggestModel.type.integerValue == 1
        || suggestModel.type.integerValue == 2) {
        
        //返回行高
        return 330 + titleSize.size.height + subTitleSize.size.height + 0.1;
    }
    //文章
    else if (suggestModel.type.integerValue == 0) {
        //推荐文章与不推荐文章返回高度
        return suggestModel.is_recommended == false ? 150 : 330 + titleSize.size.height + subTitleSize.size.height + 0.1;
    }
    //诗歌
    else if (suggestModel.type.integerValue == 5
             || suggestModel.type.integerValue == 6){
        return 350;
    } else {
        return 0;
    }
}

- (void)tableView:(UITableView *)tableView
didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    //  动画取消选中效果
    [tableView deselectRowAtIndexPath:indexPath
                             animated:YES];
    //  由于推荐详情与轮播图详情内容相同 于是同样跳转至轮播图详情控制器
    WCG_M_AutoDetailViewController *suggestDetailVC = [[WCG_M_AutoDetailViewController alloc] init];
    //  取到当前的模型
    GXSuggestModel *suggestModel = self.allWaterfallArr[indexPath.row];
    //  属性传值
    suggestDetailVC.suggestModel = suggestModel;
    suggestDetailVC.url = suggestModel.item_url;
    suggestDetailVC.titleStr = suggestModel.title;
    //  push
    [self.navigationController pushViewController:suggestDetailVC
                                         animated:YES];
}

#pragma mark - 轮播图被点击响应代理方法
- (void)collectionViewDidSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    //  轮播图详情控制器
    WCG_M_AutoDetailViewController *autoDetailVC = [[WCG_M_AutoDetailViewController alloc] init];
    //  属性传值 传一个 SuggestModel
    autoDetailVC.suggestModel = self.autoScrollArr[indexPath.item];
    autoDetailVC.url = [self.autoScrollArr[indexPath.item] item_url];
    autoDetailVC.titleStr = [self.autoScrollArr[indexPath.item] title];
    //  push
    [self.navigationController pushViewController:autoDetailVC
                                         animated:YES];
}

#pragma mark - 下午茶按钮点击响应方法
- (void)afternonnTeaButtonAction {
    //  下午茶控制器
    WCG_M_NoonTeaViewController *noonVC = [[WCG_M_NoonTeaViewController alloc] init];
    noonVC.dailyModel = self.dailyModel;
    //  push
    [self.navigationController pushViewController:noonVC
                                         animated:YES];
}

- (void)getDailyModelData {
    [GXiaNetHandle getUrl:kdailyWeb cookie:nil success:^(id result) {
        self.dailyModel = [GXDailyModel modelWithDic:result[@"daily"]];
    } failure:^(NSError *error) {
        
    }];
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    static CGFloat y;
    if (scrollView.contentOffset.y > y) {
        [UIView animateWithDuration:1 animations:^{
            self.navigationController.navigationBar.alpha = 0.8;
        }];
        y = scrollView.contentOffset.y;
    }
    if (scrollView.contentOffset.y < y) {
        [UIView animateWithDuration:1 animations:^{
            self.navigationController.navigationBar.alpha = 0;
        }];
        y = scrollView.contentOffset.y;
    }
}

@end
